// by Xeno
//#define __DEBUG__
#define THIS_FILE "fn_createrandomtargets.sqf"
#include "x_setup.sqf"

private ["_firstar", "_add", "_nn", "_pp1", "_pp2", "_fails","_left"];

_firstar = (count GVAR(target_names)) call FUNC(RandomIndexArray);
__TRACE_2("","(count d_target_names)","_firstar")
_add = [];

// TYRGHEN - Making the creation of random routes possible
if (isNil QGVAR(MainTargetsDistance)) then { GVAR(MainTargetsDistance) = -1 };

if (GVAR(MainTargetsDistance) > 0) then {
	GVAR(MainTargetsDistance) = GVAR(MainTargetsDistance) max 1200;
	_i = 1;
	_nn = _firstar select 0;
	_fails = 0;
	_left = (count GVAR(target_names) - 1);
	// TYRGHEN - We start from the random array and try to sort the array by max distance
	__TRACE("Starting route creation")
	while { _i < (count _firstar) } do {
		_pp1 = GVAR(target_names) select _nn;
		_pp2 = GVAR(target_names) select (_firstar select _i);
		if (_fails <= _left && (((_pp1 select 0) distance (_pp2 select 0)) < GVAR(MainTargetsDistance) || ((_pp1 select 0) distance (_pp2 select 0)) > (3 * GVAR(MainTargetsDistance)))) then {
			_firstar set [count _firstar, _firstar select _i];
			_firstar set [_i, -999];
			__INC(_fails);
		} else {
			_nn = _firstar select _i;
			_fails = 0;
			__DEC(_left);
		};
		__INC(_i);
	};
	__TRACE_1("Ending route creation","(count _firstar)")
	_firstar = _firstar - [-999];
} else {
	// TYRGHEN - We prevent targets to be too close to each other, but we let them be random around the map
	for "_i" from 0 to (count _firstar - 2) do {
		_nn = _firstar select _i;
		_pp1 = GVAR(target_names) select _nn;
		_pp2 = GVAR(target_names) select (_firstar select (_i + 1));
		if ((_pp1 select 0) distance (_pp2 select 0) < 1000) then {
			_add set [count _add, _nn];
			_firstar set [_i, -999];
		};
	};
};

__TRACE_1("","_add");

if (count _add > 0) then {
	_firstar = _firstar - [-999];
	_firstar = [_firstar, _add] call FUNC(arraypushstack2);
};

__TRACE_1("","_firstar");

_firstar